package com.demo.web_06;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "UserQueryServlet", urlPatterns = {"/queryUser"})
public class UserQueryServlet extends HttpServlet {

    private List<User> userList = new ArrayList<>(); // 预设用户信息列表，实际中可以从数据库获取

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String queryParam = request.getParameter("query");
        StringBuilder resultHtml = new StringBuilder("<html><body>");

        if(queryParam != null && !queryParam.trim().isEmpty()){
            for(User user : userList){
                if(user.getUsername().contains(queryParam)||String.valueOf(user.getUserId()).equals(queryParam)){
                    resultHtml.append("<p>ID: ").append(user.getUserId())
                            .append(", Username: ").append(user.getUsername())
                            .append("</p>");
                }
            }
        } else {
            resultHtml.append("Please enter a valid query parameter.");
        }

        resultHtml.append("</body></html>");

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.print(resultHtml.toString());
        writer.flush();
        writer.close();
    }

    // 示例User类
    static class User {
        public int getUserId() {
            return userId;
        }
        public void setUserId(int userId) {
            this.userId = userId;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        int userId;
        String username;
        User(int userId, String username) {
            this.userId = userId;
            this.username = username;
        }
    }
    // 初始化用户列表（示例数据）
    @Override
    public void init() throws ServletException {
        userList.add(new User(1, "Alice"));
        userList.add(new User(2, "Bob"));
        userList.add(new User(3, "Charlie"));
    }
}